import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import '../../css/dll/index.scss'
import goeasy from './goeasy'
import GoEasy from 'goeasy'
export default function Index() {
	const [input, setinput] = useState("")
	const [list, setlist] = useState([])
	const [message, setmessage] = useState({})
	const [isPressing, setIsPressing] = useState(false);
	const navigate = useNavigate();
	const refanPage = () => {
		navigate('/home/message');
	}
	var im = goeasy.im;

	useEffect(() => {
		//连接
		goeasy.connect({
			id: "003", //im必填，最大长度60字符
			data: { "avatar": "../img/liao.png", "nickname": "Neo" },
			onSuccess: function () {  //连接成功
				console.log("成功") //连接成功
			},
			onFailed: function (error) { //连接失败
				console.log("失败");
			},
		});
		getHistory()
	}, [])
	// 发送信息
	const send = () => {
		console.log(input);
		if (input != '') {
			let textMessage = im.createTextMessage({
				text: input, //消息内容
				to: {
					type: GoEasy.IM_SCENE.PRIVATE,   //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
					id: '001', //接收方用户id
					data: { "avatar": "../img/liao.png", "nickname": "Neo" } //接收方用户扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
				}
			});

			//发送消息
			im.sendMessage({
				message: textMessage,
				onSuccess: function (message) { //发送成功
					console.log("发送成功");

				},
				onFailed: function (error) { //发送失败
					console.log('发送失败');
				}
			});
			setinput("")
		}
		// else {
		// 	alert('3')
		//   }
	}
	//获取历史记录
	const getHistory = () => {
		im.history({
			id: '001',//用户id或者群id
			type: GoEasy.IM_SCENE.PRIVATE, //群聊：GoEasy.IM_SCENE.GROUP, 客服：GoEasy.IM_SCENE.CS,

			limit: 10, //可选项，返回的消息条数，默认为10条，最多30条
			onSuccess: function (result) {
				//单聊历史消息result示例
				console.log(result['content']);
				setlist(result.content)
			}
		});
	}
	useEffect(() => {
		// 监听和接收单聊消息
		goeasy.im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);
		goeasy.im.on(GoEasy.IM_EVENT.MESSAGE_RECALLED, onMessageRecalled);
	}, [])

	useEffect(() => {
		return () => {
			// 销毁监听和接收单聊消息
			goeasy.im.off(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);
		}
	}, [])
	var onMessageRecalled = (message) => {

		getHistory()
	}
	var onPrivateMessageReceived = (message) => {
		getHistory()
	};
	//时间
	const formatDate = (dates) => {
		const date = new Date(dates)
		const hours = ("0" + date.getHours()).slice(-2);
		const minutes = ("0" + date.getMinutes()).slice(-2);
		const day = ("0" + date.getDate()).slice(-2);
		const month = ("0" + (date.getMonth() + 1)).slice(-2);
		const year = date.getFullYear();
		return year + '年' + month + '月' + day + '日' + hours + ":" + minutes;
	};
	// 弹出框的逻辑
	let pressTimer;
	const showPopup = (item) => {
		setmessage(item)
		setIsPressing(true);
	};
	const startPressTimer = (event, item) => {
		// event.preventDefault();
		pressTimer = setTimeout(() => { showPopup(item) }, 1000); // 设置长按时间阈值为2秒

	};
	const cancelPressTimer = (event) => {
		// event.preventDefault();
		clearTimeout(pressTimer); // 取消定时器
		// setIsPressing(false);
	};


	return (
		<div style={{
			width: '100%',
			height: '41.6rem',
			// color: '#fff',
			position: 'absolute',
			backgroundImage: 'url(../img/bei.png)',
			backgroundSize: '100% 100%',
		}}>
			<div

			>
				<div >
					<img style={{
						margin: '0.6rem',
						float: 'left',
					}} src='../imgs/youjian.png' alt="" onClick={refanPage} />
					<span className='dll_index_top'>田二妞</span>
				</div>
			</div>
			<div className='liuliu'>
				<img src="../img/liao.png" alt="" />

				{list.map((item, index) => {
					return <div key={index}>
						<div className={item.recalled === false ? 'xian' : 'xiao'}>

							<div className={item.senderId === '001' ? 'left' : 'right'}
								onMouseDown={(e) => { startPressTimer(e, item) }}
								onMouseUp={(e) => { cancelPressTimer(e) }}
								onTouchStart={(e) => startPressTimer(e, item)}
								onTouchEnd={(e) => { cancelPressTimer(e) }}
							>

								{
									item.type === "text" ? <p><span className={item.payload.text.length > 1000 ? 'bianf' : 'biaop'}>{item.payload.text} </span>
										<img src={item.payload.text} className={item.payload.text.length > 1000 ? 'biaop' : 'bianf'} />
									</p> : ""
								}
							</div>
						</div>
					</div>
				})}
			</div>
			<div className='dll_send'>
				<input type="text" value={input}
					onChange={(e) => { setinput(e.target.value) }} name="" id=""
					onKeyDown={(e) => {
						if (e.keyCode === 13) {
							send()
						}
					}} />
				{/* <button onClick={() => { send() }}> 发送</button> */}
				{/* <h4>{formatDate(item.timestamp)}</h4> */}
			</div>
		</div>
	)
}

